<?php

namespace app\api\model;

use think\Exception;
use think\Model;
use think\Db;
use think\Validate;

class Claimreports extends Model
{
    public function getlist()
    {
        echo "!@324";
    }

    public function types()
    {
        $types = [
            "0" => array("type"=>"4","name"=>"交通事故"),
            "1" => array("type"=>"5","name"=>"法院起诉"),
            "2" => array("type"=>"6","name"=>"工伤资料"),
            "3" => array("type"=>"7","name"=>"第三方已赔付"),
        ];
        return $types;
    }

    public function cost()
    {
        $cost = [
            "0" => array("type"=>"8","name"=>"万元以上"),
            "1" => array("type"=>"9","name"=>"万元以下"),
        ];
        return $cost;
    }

    public function payFor()
    {
        $cost = [
            "0" => array("type"=>"13","name"=>"赔付给伤者"),
            "1" => array("type"=>"14","name"=>"赔付给垫付人"),
        ];
        return $cost;
    }

    /**
     * 资料配置项，（费用和特殊资料）
     * 2021-01-11
     */

    public function getSet($where,$str)
    {
        $data = Db::name("claim_company_setting")
            ->alias("a")
            ->join("claim_setting u","a.setting_id=u.id")
            ->where("a.company_id",$where['company_id'])->where("a.status",$where['status'])
            ->where("u.type","in",$str)
            ->group("u.type")
            ->field("u.type,name")
            ->select();
        return $data;
    }

    /**
     * 操作日志
     * 2021-01-11
     * @param claim_id 报案id
     * @param remarks 操作内容
     */
    public function addLog($claim_id,$remarks)
    {
        $data['claim_id'] = $claim_id;
//        $data['admin_id'] = $this->auth->id;
//        $data['admin_name'] = Db::name("admin")->where('id',$this->auth->id)->value("nickname");
        $data['remarks'] = $remarks;
        $data['add_time'] = time();
        return  Db::name("claim_report_log")->insert($data);
    }

    /**
     * 理赔列表
     * 2021-01-14
     */
    public function claimList($where,$offset)
    {
        $data = Db::name("claim_report")
            ->order("claim_status desc,update_time desc")
            ->field("id,policy_num,report_num,name,applicant_name,applicant_tel,id_num,tel,product_name,company_id,happen_time,report_time,status,claim_status")
            ->where($where)
            ->limit($offset,10)
            ->select();
        $company = config('companys.list');
        foreach($data as $key => $val) {
            if(!empty($val['company_id'])) {
                $data[$key]['company_name'] = $company[$val['company_id']];
            }
        }
        $res['total'] = Db::name("claim_report")->where($where)->count();
        $res["list"] = $data;
        return $res;
    }

    /**
     * 报案提交时 获取配置项及条目
     */
    public function setting($id)
    {
        $claim = Db::name("claim_report")->where("id",$id)->find();

        $map1="";
        $map2="";
        if($claim['insur_id']=="1" && $claim['pay_for']!=""){
            switch ($claim['pay_for']) {
                case "13":
                    $payfor = 14;
                    break;
                case "14":
                    $payfor = 13;
                    break;
            }
            $map1 = "a.type != ".$payfor." or a.type = 1 or a.type is null";
//            $where['a.type'] = array(array('neq',$payfor),array('eq',"1"),array("eq","null"), 'or');  // cate_id=1 指团意险时，区分赔付给垫付人和伤者  pay_for 字段，赔给伤者，赔给个人，1代表通用
        }
        if($claim['cost'] != "") {
            switch ($claim['cost']) {
                case "8":
                    $cost = 9;
                    break;
                case "9":
                    $cost = 8;
                    break;
            }
            $map2 = "a.type != ".$cost." or a.type = 1 or a.type is null";
        }
//            $where['a.type'] = array(array('neq',$cost),array('eq',"1"),array("","null"), 'or');    // 其他时候，根据type 区分 万元以上及万元以下 cost 万元 以上/以下， 1代表通用
        $data = $this->getAll($claim,$map1,$map2);
        return $data;
    }

    /**
     * 2021-01-20
     * 理赔资料详情页面，如果重新选择万元，或者赔付选择，重新获取配置项及条目
     * @param $param
     * @param pay_for 赔付给伤者或者个人
     * @param cost  万元以上，万元以下
     * @param company_id 保司id
     * @param insur_id 险种id
     * @return array
     */
    public function newGet($param)
    {
        $map1="";
        $map2="";
        $payfor = "";
        if(isset($param['pay_for'])){
            switch ($param['pay_for']) {
                case "13":
                    $payfor = 14;
                    break;
                case "14":
                    $payfor = 13;
                    break;
            }
            $map1 = "a.type != ".$payfor." or a.type = 1 or a.type is null";
        }
        if(isset($param['cost'])) {
            switch ($param['cost']) {
                case "8":
                    $cost = 9;
                    break;
                case "9":
                    $cost = 8;
                    break;
            }
            $map2 = "a.type != ".$cost." or a.type = 1 or a.type is null";
        }
        $data = $this->getAll($param,$map1,$map2,$payfor);
        return $data;
    }

    /**
     * 2021-01-20
     * 获取配置及条目
     * @param $claim
     * @param null $map1
     * @param null $map2
     * @return array
     */
    public function getAll($claim,$map1=null,$map2=null,$pay=null)
    {
        $where['a.company_id'] = $claim['company_id'];
        $where['a.status'] = $claim['insur_id'];
        //其他所有资料（包括特殊资料）
        //分组查询，先查配置项，再循环查条目
        $cate = Db::name("claim_company_setting")->where("company_id",$claim['company_id'])->where("status",$claim['insur_id'])->order("cate_id asc")->field("cate_id")->select();
        $cate = array_unique(array_column($cate,"cate_id"));
        //cate_id 代表配置项 id
        $data=[];
        foreach($cate as $key=>$val){
            $list = [];
            $list['cate_id'] = $val;
            if($pay=="13" && $val=="3"){
                $list['cate_name'] = "垫付人资料";
            } else {
                $list['cate_name'] = Db::name("claim_cate")->where("id", $val)->value("name");
            }
            $list["list"] =Db::name("claim_company_setting")
                ->alias("a")
                ->join("claim_setting u","a.setting_id=u.id")
                ->where("u.cate_id",$val)
                ->where($where)
                ->where($map1)
                ->where($map2)
                ->order("a.cate_id asc")
                ->field("u.id,u.cate_id,u.name,u.desc,u.type,u.file_url,imgs as img_url,'' as imgs")
                ->select();
            if(!empty($list["list"])) {
                $data[]=$list;
            }
        }
        return $data;
    }

    /**
     * 公用，获取理赔老师
     * 2021-01-20
     * @param company_id 保司
     */
    public function getTeacher($id)
    {
        $teacher = Db::name("claim_persons")->where("id",$id)->select();
        return $teacher;
    }

    /**
     * 理赔资料提交/保存，资料条目处理成三维数组，转json
     * 2021-01-22
     */
    public function turnData($res)
    {
        $payfor = "";
        $cost = "";
        if(isset($arr['pay_for'])) {
            $payfor = $res['pay_for'];
        }
        if(isset($arr['cost'])){
            $cost = $res['cost'];
        }
        $cates = array_unique(array_column($res,"cate_id"));
        sort($cates);
        for($i=0;$i<count($cates);$i++) {
            //尚不确定 团意险（即 区分垫付人及伤者时）,是否依然区分万元以上万元以下，现在是都区分
            if($cost =="9" && ($cates[$i]=="6" || $cates[$i]=="7")){
                continue;
            }
            $arr['cate_id'] = $cates[$i];
            if($cates[$i]=="3" && $payfor=="14") {
                $arr['cate_name'] = "垫付人资料";
            } else {
                $cate_name = Db::name("claim_cate")->where("id",$cates[$i])->value("name");
                $arr['cate_name'] = mb_substr($cate_name,0,mb_strlen($cate_name)-2);
            }
            $list = [];
            foreach($res as $k => $v){
                if($cates[$i]==$v['cate_id']) {
                    $list[] = $v;
                }
            }
            $arr['list'] = $list;
            $data[] = $arr;
        }
        return $data;
    }

    /**
     * 理赔审核-获取理赔填写的资料
     * 2021-01-22
     */
    public function getClaim($param)
    {
        $data = Db::name("claim_info")->where("claim_id",$param['claim_id'])->find();
        return $data;
    }

    /**
     * 获取操作日志
     * 2021-01-22
     * @param claim_id
     */
    public function getLog($param)
    {
        $data = Db::name("claim_report_log")
                ->where("claim_id",$param['claim_id'])
                ->order("id desc")
                ->field("admin_name,remarks,FROM_UNIXTIME(add_time,'%Y-%m-%d %H:%i:%s') as add_time")
                ->select();
        return $data;
    }

    /**
     * 生成资料文件目录
     * 2021-01-18
     */
    public function getWord($param,$status=null)
    {
        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $section = $phpWord->addSection();

        $fontStyle = new \PhpOffice\PhpWord\Style\Font();
        $spaceStyle = new \PhpOffice\PhpWord\Style\Font();
//        $fontStyle->setBold(true);
        $fontStyle->setName('SimSun');
        $fontStyle->setSize(14);
        $fontStyle->setSpacing(20);

        $spaceStyle->setSize(18);
        $spaceStyle->setSpacing(20);
        $spaceStyle->setLineHeight(120);

        $this->company = config("companys.list");

        if($status=="1"){
            if($param['status']=="1"){
                switch ($param['pay_for']) {
                    case "13":
                        $typeId = 14;
                        break;
                    case "14":
                        $typeId = 13;
                        break;
                }
            } else {
                switch ($param['cost']) {
                    case "8":
                        $typeId = 9;
                        break;
                    case "9":
                        $typeId = 8;
                        break;
                }
            }
            unset($param['cost']);
            unset($param['pay_for']);
        } else {
            $ids = explode("-",$param['company_id']);
            $typeId = $ids[1];  //获取type 类型id，判断 万元以上、万元以下
            $typeName = "";
            switch($typeId) {
                case "8":
                    $typeId = 9;//type 为8，万元以上，剔除为9 万元以下的条目
                    break;
                case "9":
                    $typeId = 8;//type 为8，万元以下，剔除为9 万元以下的条目
                    break;
                case "11":
                    $typeId = 12;//type 为11，5000元以上，剔除为12 5000元以下的条目
                    break;
                case "12":
                    $typeId = 11;//type 为12，5000元以上，剔除为11 5000元以下的条目
                    break;
                case "13":
                    $typeId = 14;//type 为13，个人赔付，剔除为14 垫付人的条目
                    break;
                case "14":
                    $typeId = 13;//type 为14，垫付人，剔除为13 个人的条目
                    break;

            }
            $param['company_id'] = $ids[0]; //重新赋值保司id
        }


        $insur_name = Db::name("insur")->where("status",$param['status'])->value("name");

        //标题
        $title = $this->company[$param['company_id']] .$insur_name;
//        $section->addTitle($title,0);

        //获取保司险种下所有配置项
        //补充材料
        $cate1 = Db::name("claim_company_setting")->where($param)->where("cate_id","1")->group("cate_id")->field("cate_id,setting_id")->select();
        if(!empty($cate1)) {
            $section->addText("报案补充资料")->setFontStyle($spaceStyle);
            foreach($cate1 as $key => $val) {
                $name = Db::name("claim_setting")->where("id",$val['setting_id'])->value("name");
                $section->addText("□".$name)->setFontStyle($fontStyle);
            }
        }
        //理赔资料
        $cate2 = Db::name("claim_company_setting")->where($param)->where("cate_id","not in","1,8")->group("cate_id")->field("cate_id,setting_id")->select();

        //特殊资料
        $cate3 = Db::name("claim_company_setting")->where($param)->where("cate_id","8")->field("cate_id,setting_id")->select();

        $special_list = [];
        $data['supplement'] = [];
        $where = [
            "a.company_id"=> $param['company_id'],
            "a.status"    => $param['status']
        ];

        foreach($cate2 as $key => $val) {
            //配置项名称
            $setting_name = Db::name("claim_cate")->where('id',$val['cate_id'])->value("name");
            //金额以下时，去掉伤残和伤亡资料
            if($typeId=="8" || $typeId == "13" && ($val['cate_id']=="6" || $val['cate_id']=="7")) {
                unset($cate2[$key]);
                continue;
            }
            $where['a.cate_id'] = $val['cate_id'];
            $setting_list = $this->getlists($where);
            //根据配置项 查询当前配置项下条目

            //理赔材料（总的配置项及配置项下条目，配置项作为标题，条目拼接成一段）
            //医院资料，单独判断
            if($val['cate_id']=="2") {
                $section->addText("医院资料")->setFontStyle($spaceStyle);

                $menzhen = [];
                $zhuyuan = [];
                $tongyong = [];
                $set['title'] = mb_substr($setting_name,0,mb_strlen($setting_name)-2);
                foreach($setting_list as $k => $v) {
                    if($v['original_status'] == "1") {
                        $name = $v['name']."（原件）";
                    } elseif ($v['original_status'] == "2") {
                        $name= $v['name']."（复印件）";
                    } elseif ($v['original_status'] == "3") {
                        $name = $v['name']."（复印件加盖公章）";
                    }
                    if($v['type'] == "1") {
                        $tongyong[] = $name;
                    } elseif ($v['type'] == "2") {
                        $menzhen[] = $name;
                    } elseif ($v['type'] == "3") {
                        $zhuyuan[] = $name;
                    }
                }
                $one = "";
                $two = "";
                if((!empty($menzhen) || !empty($zhuyuan)) && !empty($tongyong)) {
                    $one = "1.";
                    $two = "2.";
                }
                if(!empty($menzhen) && !empty($zhuyuan)) {
                    $one = "1.";
                    $two = "2.";
                }
                $hos = "";
                $cont = [];
                $hos1 = "";
                $cont1 = [];
                $hos2 ="";
                $cont2 = [];
                if(!empty($tongyong)){

                    if(!empty($menzhen)) {
                        $hos = $one."涉及到门诊时，需提供的资料";
                        $cont = array_merge($menzhen,$tongyong);
                    } else {
                        $hos = $one."涉及到门诊时，需提供的资料";
                        $cont = $tongyong;
                    }
                    if($hos != ""){
                        $section->addText($hos)->setFontStyle([
                            'size' => 16
                        ])->setLineHeight(100);
                    }

                    foreach($cont as $key => $val){
                        $section->addText("□".$val)->setFontStyle($fontStyle);
                    }

                    if(!empty($zhuyuan)) {
                        $hos1 = $two."涉及到住院时，需提供的资料";
                        $cont1 = array_merge($zhuyuan,$tongyong);
                    } else {
                        $hos1 = "涉及到住院时，需提供的资料";
                        $cont1 = $tongyong;
                    }
                    if($hos1 != ""){
                        $section->addText($hos1)->setFontStyle([
                            'size' => 16
                        ])->setLineHeight(100);
                    }

                    foreach($cont1 as $key => $val){
                        $section->addText("□".$val)->setFontStyle($fontStyle);
                    }
                    if(empty($menzhen) && empty($zhuyuan)) {
                        $hos2 = "涉及到门诊、住院时，需提供的资料";
                        $cont2 = $tongyong;
                    }
                    if($hos2 != ""){
                        $section->addText($hos2)->setFontStyle([
                            'size' => 16
                        ])->setLineHeight(100);
                    }

                    foreach($cont2 as $key => $val){
                        $section->addText("□".$val)->setFontStyle($fontStyle);
                    }

                } else {
                    if(!empty($menzhen)) {
                        $hos2 = $one."涉及到门诊时，需提供的资料";
                        $cont2 = $menzhen;
                        $section->addText($hos2)->setFontStyle([
                            'size' => 16
                        ])->setLineHeight(100);

                        foreach($cont2 as $key => $val){
                            $section->addText("□".$val)->setFontStyle($fontStyle);
                        }
                    }
                    if(!empty($zhuyuan)) {
                        $hos2 = "涉及到住院时，需提供的资料";
                        $cont2 = $zhuyuan;

                        $section->addText($hos2)->setFontStyle([
                            'size' => 16
                        ])->setLineHeight(100);

                        foreach($cont2 as $key => $val){
                            $section->addText("□".$val)->setFontStyle($fontStyle);
                        }
                    }
                }
//                $section->addText("□".$set['set_list'])->setFontStyle([
//                    'size' => 13
//                ])->setLineHeight(100);
            } else {
                foreach($setting_list as $k => $v) {
                    if($v['type']==$typeId && $val['cate_id']=="5" && $v['type']!="1"){
                        unset($setting_list[$k]);
                        continue;
                    }
                    if($v['type']==$typeId && $val['cate_id']=="3" && $v['type']!="1"){
                        unset($setting_list[$k]);
                        continue;
                    }
                }
                if(empty($setting_list)) {
                    unset($cate2[$key]);
                } else {
                    if($typeId=="13"){
                        $set['title'] = "垫付人资料";
                    } else {
                        $set['title'] = mb_substr($setting_name,0,mb_strlen($setting_name)-2);
                    }
                    $section->addText($set['title'])->setFontStyle($spaceStyle);
                    foreach($setting_list as $k => $v) {
                        if($v['original_status'] == "1") {
                            $name = $v['name']."（原件）";
                        } elseif ($v['original_status'] == "2") {
                            $name = $v['name']."（复印件）";
                        } elseif ($v['original_status'] == "3") {
                            $name = $v['name']."（复印件加盖公章）";
                        }
                        $section->addText("□".$name)->setFontStyle($fontStyle);
                    }
                }
            }
        }

        if(!empty($cate3)){
            $where['a.cate_id'] = 8;
            $setting_list = $this->getlists($where);

            $types  = array_column($setting_list,"type");
            $types = array_unique($types);
            sort($types);  //重新排序
            $section->addText("特殊资料")->setFontStyle($spaceStyle);

            //根据类别 及 配置项条目查询中的条目id，处理数据
            for($i=0;$i<count($types);$i++) {

                $setting_id = implode(',',array_column($setting_list,"setting_id"));

                $special['type_name'] = Db::name("claim_type")->where("id",$types[$i])->value("name");

                $type_list = Db::name("claim_setting")->where("id","in",$setting_id)->where("type",$types[$i])->order("sort asc")->field("name,original_status")->select();
                foreach($type_list as $key=>$val){
                    if($val['original_status'] == "1") {
                        $name = $val['name']."（原件）";
                    } elseif ($val['original_status'] == "2") {
                        $name = $val['name']."（复印件）";
                    } elseif ($val['original_status'] == "3") {
                        $name = $val['name']."（复印件加盖公章）";
                    }
                    $section->addText("□".$name)->setFontStyle($fontStyle);
                }
            }
        }

        $rootDir = ROOT_PATH . '/public';

        $baseDir = '/uploads/words/';

        $dir = $rootDir . $baseDir;

        if (!is_dir($dir)) @mkdir($dir, 0777, true);

        $filename = iconv('utf-8', 'gbk',$title . '.docx'); //md5(uniqid(true) . microtime(true)) . '.doc';

        $phpWord->save($dir . $filename, 'Word2007', false);

        return $_SERVER['HTTP_HOST'] .$baseDir . $title.".docx";
    }

    /**
     * 获取所有条目
     */
    public function getlists($where)
    {
        $setting_list = Db::name("claim_company_setting")->alias("a")
            ->join("claim_setting u","a.setting_id=u.id")
            ->where($where)
            ->field("name,original_status,a.type,setting_id")
            ->order("u.sort asc")
            ->select();
        return $setting_list;
    }
}

?>